package com.sy.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sy.dto.CoursePageQueryDTO;
import com.sy.pojo.Course;
import com.sy.pojo.CourseType;
import com.sy.pojo.CourseUser;
import com.sy.pojo.Coursedetail;
import com.sy.result.PageResult;
import com.sy.result.Result;
import com.sy.service.CourseService;
import com.sy.service.CourseTypeService;
import com.sy.service.CourseUserService;
import com.sy.service.CoursedetailService;
import com.sy.utils.FastDFSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.time.LocalDateTime;
import java.util.List;

@Api(tags = "课程管理相关接口")
@Slf4j
@RestController
@RequestMapping("/admin/course")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @Autowired
    private CourseTypeService courseTypeService;
    @Autowired
    private CourseUserService courseUserService;
    @Autowired
    private CoursedetailService coursedetailService;

    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;//文件服务器地址

    //课程查询
    @GetMapping("findAll")
    @ApiOperation("课程分页查询")
    public Result<PageResult> findAll(CoursePageQueryDTO coursePageQueryDTO){
        //打印请求数据日志
        log.info("课程分页查询：{}",coursePageQueryDTO);
        //调用业务获取分页查询

        PageResult pageResult= courseService.findAll(coursePageQueryDTO);

        return Result.success(pageResult);

    }

    @GetMapping("courseTypeList")
    @ApiOperation("课程类型查询")
    public Result<List<CourseType>> courseTypeList(){
        List<CourseType> courseTypeList=courseTypeService.list();
        return Result.success(courseTypeList);
    }

    //文件上传fastDFS的方法
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam(name = "file") MultipartFile file) {
        //1、取文件的扩展名
        String originalFilename = file.getOriginalFilename();
        //文件后缀名
        String extName =
                originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try {
            //2、执行上传处理
            String path = FastDFSClient.uploadFile(file.getBytes(), extName);
            //3、拼接返回的 url 和 ip 地址，拼装成完整的 url
            String url = FILE_SERVER_URL + path;
            return Result.success(url);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败");
        }
    }

    @ApiOperation("文件删除")
    @PostMapping("/deleteFile")
    @ApiImplicitParam(name = "fileName",value = "文件名称",required = true,dataTypeClass = String.class)
    public Result<String> deleteFile(String fileName) {
        try {
            FastDFSClient.deleteFile(fileName);
            return Result.success();
        } catch (Exception e) {
            throw new RuntimeException("删除失败");
        }
    }
    //添加课程
    @ApiOperation("添加课程")
    @PostMapping("/save")
    public Result<String> save(@RequestBody Course course) {
        log.info("课程添加：{}",course);
        try {
            course.setCreateTime(LocalDateTime.now());
            courseService.save(course);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("课程添加失败");
        }
    }

    @ApiOperation("修改课程")
    @PostMapping("/update")
    public Result<String> update(@RequestBody Course course) {
        log.info("课程修改：{}",course);
        try {
            //先查询要修改的课程的原本的信息
            Course oldCourse=courseService.getById(course.getCid());
            //修改课程
            courseService.save(course);
            //对比要修改的课程封面和原本的图片名称是否不一致
            if(!course.getCourseImage().equals(oldCourse.getCourseImage())){
                //如果要修改的图片名称和原本的图片名称不一致，那么去把图片删除
                FastDFSClient.deleteFile(oldCourse.getCourseName());
            }
            //对比要修改的课程视频和原本的视频名称是否不一致
            if(!course.getCourseVideo().equals(oldCourse.getCourseVideo())){
                //如果要修改的视频名称和原本的视频名称不一致，那么去把视频删除
                FastDFSClient.deleteFile(oldCourse.getCourseVideo());
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("课程添加失败");
        }
    }

    @PostMapping("delete")
    @Transactional
    @ApiOperation("课程的删除")
    @ApiImplicitParams({@ApiImplicitParam(value = "课程的id集合",name = "cids",required = true,dataTypeClass = List.class)})
    public Result<String> delete(@RequestBody List<Integer> cids) {
        /**
         * 删除课程前两个问题
         * 1.当前的课程下是否存在课程明细
         * 2.当前课程下是否存在以后购买
         */
        log.info("课程删除：{}",cids);
        try {
            boolean flag=true;
            for (Integer cid : cids) {
                //课程完整信息的查询
                Course course=courseService.getById(cid);
                //1.先查询所删除的课程有没有被用户所选，被选的话不能删除
                LambdaQueryWrapper<CourseUser> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(CourseUser::getCid,cid);
                int count=courseUserService.count(queryWrapper);
                if(count>0){
                    flag=false;
                    //说明这个课程被用户选择过了，不能删除
                    return Result.error("【"+course.getCourseName()+"】课程被用户选择，不能删除");
                }
                //2.在查询课程下有没有课程明细，有课程明细也不能删除
                LambdaQueryWrapper<Coursedetail> queryWrapper1=new LambdaQueryWrapper<>();
                queryWrapper1.eq(Coursedetail::getCid,cid);
                int counted = coursedetailService.count(queryWrapper1);
                if(counted>0){
                    flag=false;
                    //说明这个课程下有课程明细，不能删除
                }
            }
            if(flag){
                //根据课程cid批量删除
                List<Course> courseList=courseService.listByIds(cids);
                //根据id删除
                courseService.removeByIds(cids);
                for (Course course : courseList) {
                    FastDFSClient.deleteFile(course.getCourseImage());//删除图片
                    FastDFSClient.deleteFile(course.getCourseVideo());//删除视频
                }
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("课程删除失败");
        }
    }
}
